package com.gdpu.watermelontimer.viewmodel

import android.app.Application
import android.content.Context
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.gdpu.watermelontimer.data.*
import com.gdpu.watermelontimer.timer.PomodoroTimer
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*

class MainViewModel(application: Application) : AndroidViewModel(application) {
    
    private val database = AppDatabase.getDatabase(application)
    private val taskDao = database.taskDao()
    private val sessionDao = database.pomodoroSessionDao()
    
    private val pomodoroTimer = PomodoroTimer(application)//进度条
    
    // 当前登录用户ID
    private val userId: Long = application.getSharedPreferences("user", Context.MODE_PRIVATE).getLong("userId", 0L)
    
    // LiveData
    val tasks: LiveData<List<Task>> = taskDao.getTasksByUserId(userId)
    val timerState: LiveData<PomodoroTimer.TimerState> = pomodoroTimer.timerState
    val currentTime: LiveData<Long> = pomodoroTimer.currentTime
    val progress: LiveData<Float> = pomodoroTimer.progress
    
    private val _selectedTask = MutableLiveData<Task?>()
    val selectedTask: LiveData<Task?> = _selectedTask
    
    private val _todayPomodoros = MutableLiveData<Int>()
    val todayPomodoros: LiveData<Int> = _todayPomodoros
    
    init {
        loadTodayPomodoros()
    }
    
    // 任务管理
    fun addTask(name: String, description: String, category: String, priority: Task.Priority, estimatedPomodoros: Int) {
        viewModelScope.launch {
            val task = Task(
                name = name,
                description = description,
                category = category,
                priority = priority,
                estimatedPomodoros = estimatedPomodoros,
                userId = userId
            )
            taskDao.insertTask(task)
        }
    }
    
    fun updateTask(task: Task) {
        viewModelScope.launch {
            taskDao.updateTask(task.copy(updatedAt = System.currentTimeMillis()))
        }
    }
    
    fun deleteTask(task: Task) {
        viewModelScope.launch {
            taskDao.deleteTask(task)
        }
    }
    
    fun selectTask(task: Task?) {
        _selectedTask.value = task
    }
    
    fun markTaskAsCompleted(taskId: Long) {
        viewModelScope.launch {
            taskDao.markTaskAsCompleted(taskId)
        }
    }
    
    // 番茄钟控制
    fun startWorkSession(taskId: Long? = null) {
        pomodoroTimer.startWorkSession(taskId)
    }
    
    fun startShortBreak() {
        pomodoroTimer.startShortBreak()
    }
    
    fun startLongBreak() {
        pomodoroTimer.startLongBreak()
    }
    
    fun pauseTimer() {
        pomodoroTimer.pauseTimer()
    }
    
    fun resumeTimer() {
        pomodoroTimer.resumeTimer()
    }
    
    fun stopTimer() {
        pomodoroTimer.stopTimer()
    }
    
    fun skipSession() {
        pomodoroTimer.skipSession()
    }
    
    fun resetTimer() {
        pomodoroTimer.resetTimer()
    }
    
    // 会话管理
    fun saveCurrentSession() {
        pomodoroTimer.getCurrentSession()?.let { session ->
            viewModelScope.launch {
                val sessionId = sessionDao.insertSession(session)
                
                // 如果是工作会话且完成了，增加任务的番茄钟计数
                if (session.sessionType == PomodoroSession.SessionType.WORK && 
                    session.isCompleted && 
                    session.taskId != null) {
                    taskDao.incrementCompletedPomodoros(session.taskId)
                }
                
                loadTodayPomodoros()
            }
        }
    }
    
    private fun loadTodayPomodoros() {
        viewModelScope.launch {
            val calendar = Calendar.getInstance()
            calendar.set(Calendar.HOUR_OF_DAY, 0)
            calendar.set(Calendar.MINUTE, 0)
            calendar.set(Calendar.SECOND, 0)
            calendar.set(Calendar.MILLISECOND, 0)
            val startOfDay = calendar.timeInMillis
            
            calendar.add(Calendar.DAY_OF_MONTH, 1)
            val endOfDay = calendar.timeInMillis
            
            sessionDao.getCompletedWorkSessionsCount(startOfDay, endOfDay).observeForever { count ->
                _todayPomodoros.value = count
            }
        }
    }
    
    // 数据统计
    fun getSessionsByDateRange(startDate: Date, endDate: Date): LiveData<List<PomodoroSession>> {
        return sessionDao.getSessionsByDateRange(startDate.time, endDate.time)
    }
    
    fun getSessionsByTask(taskId: Long): LiveData<List<PomodoroSession>> {
        return sessionDao.getSessionsByTask(taskId)
    }
    
    // 设置管理
    fun updateTimerSettings(
        workDuration: Long,
        shortBreakDuration: Long,
        longBreakDuration: Long,
        longBreakInterval: Int
    ) {
        pomodoroTimer.updateSettings(workDuration, shortBreakDuration, longBreakDuration, longBreakInterval)
    }
    
    // 工具方法
    fun formatTime(milliseconds: Long): String {
        val minutes = (milliseconds / 1000) / 60
        val seconds = (milliseconds / 1000) % 60
        return String.format("%02d:%02d", minutes, seconds)
    }
    
    fun getSessionTypeText(sessionType: PomodoroSession.SessionType): String {
        return when (sessionType) {
            PomodoroSession.SessionType.WORK -> "工作"
            PomodoroSession.SessionType.SHORT_BREAK -> "短休息"
            PomodoroSession.SessionType.LONG_BREAK -> "长休息"
        }
    }
    
    fun getPriorityText(priority: Task.Priority): String {
        return when (priority) {
            Task.Priority.ROUTINE -> "日常"
            Task.Priority.IMPORTANT -> "重要"
            Task.Priority.URGENT -> "急"
        }
    }
    
    fun getPriorityColor(priority: Task.Priority): Int {
        return when (priority) {
            Task.Priority.ROUTINE -> android.graphics.Color.parseColor("#8BC34A") // 绿色
            Task.Priority.IMPORTANT -> android.graphics.Color.parseColor("#FF9800") // 橙色
            Task.Priority.URGENT -> android.graphics.Color.parseColor("#F44336") // 红色
        }
    }
    
    fun getCurrentSession(): PomodoroSession? {
        return pomodoroTimer.getCurrentSession()
    }
    
    fun cleanup() {
        pomodoroTimer.cleanup()
    }
    
    override fun onCleared() {
        super.onCleared()
        pomodoroTimer.cleanup()
    }
} 